/**
 * 对于一些附加插件的绑定用,保持和直接引入js的开发体验一致
 */
define([
    "jquery",
    "knockout",
    "komapping",
    "knockout.validation",
    "koVLangZhCn",
], function ($, ko, komapping, koValidation, koVLangZhCn) {
    //挂载mapping插件为ko属性
    ko.mapping = komapping;
    //挂载验证
    ko.validation = koValidation;
    //给验证注入多语言中文 zh-CN ，默认语言：en-us
    koVLangZhCn;

    //添加针对img标签图片加载错误的处理
    ko.bindingHandlers.handleImgError = {
        init: function (
            element,
            valueAccessor,
            allBindings,
            viewModel,
            bindingContext
        ) {
            var valueAccessor = valueAccessor();
            var imgList;
            if (ko.isObservableArray(valueAccessor)) {
                imgList = valueAccessor();
            } else {
                imgList = valueAccessor;
            }
            var allBindings = allBindings();
            var index = 0;
            element.onerror = function (e) {
                //如果备选图片路径都用完了，停止处理，这样就不报错了
                if (index >= imgList.length) {
                    element.alt = "图片加载失败";
                    return;
                }
                var img = imgList[index];
                if (allBindings.attr && ko.isObservable(allBindings.attr.src)) {
                    allBindings.attr.src(img);
                } else {
                    element.src = img;
                }

                index++;
            };
        },
    };
    return "挂载子插件成功";
});
